//
//  HJModifyUIDController.m
//  KaiChat
//
//  Created by lx on 2023/12/18.
//

#import "HJModifyUIDController.h"
#import "QMUITextField.h"
#import "HJMinePresent.h"
#import "HJUserModel.h"
#import "HJUIAlertController.h"
#import "QMUIButton.h"
#import "HJUIDTipView.h"
#import "HJAlertController.h"

@interface HJModifyUIDController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *mainView;
@property (nonatomic, weak) HJBarButton *doneButton;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, weak) UILabel *oldUIDValueLabel;
@property (nonatomic, weak) HJUIDTipView *tipView;
@property (nonatomic, assign) CGFloat tipViewH;
@property (nonatomic, weak) UIView *ruleView;
@property (nonatomic, weak) UIView *UIDView;
@property (nonatomic, assign) BOOL showTip;

@end

@implementation HJModifyUIDController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"UID";
    self.navigationBar.lineView.hidden = YES;
    CGFloat bottomMagrin = 0;
    
    self.tipViewH = 40;    
    HJBarButton *doneButton = [HJBarButton barButtonWithTitle:@"Done" color:UIColor.tj_mainColor target:self action:@selector(didClickDoneButton)];
    [doneButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [self.navigationBar.contentView addSubview:doneButton];
    doneButton.enabled = NO;
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(40);
        make.centerY.offset(0);
        make.height.offset(40);
    }];

    self.mainView = [UIScrollView addToView:self.view];
    self.mainView.frame = CGRectMake(0, KNavBarHight, KScreenWidth, KScreenHeight - KNavBarHight - bottomMagrin);
    self.mainView.backgroundColor = UIColor.tj_backgroundColor;
    CGSize contentSize = self.mainView.bounds.size;
    self.mainView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.mainView.contentSize = contentSize;
    self.mainView.showsVerticalScrollIndicator = NO;
    self.mainView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
 
    UIView *contentView = [[UIView alloc] init].addTo(self.mainView);
    contentView.backgroundColor = UIColor.tj_backgroundColor;
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(contentSize.width);
        make.height.offset(contentSize.height);
    }];
    
    UIView *oldUIDView = [UIView addToView:contentView];
    oldUIDView.layer.borderColor = UIColor.tj_separatorColor.CGColor;
    oldUIDView.layer.cornerRadius = 10;
    oldUIDView.layer.masksToBounds = YES;
    oldUIDView.layer.borderWidth = 0.7;
    [oldUIDView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(20);
        make.height.offset(50);
    }];
    
    UILabel *oldUIDLabel = [UILabel lableWithSuperView:oldUIDView font:UIFontMediumMake(14) color:UIColor.tj_868391Color title:@"Old UID" textAlignment:NSTextAlignmentLeft];
    [oldUIDLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.centerY.offset(0);
    }];
    
    UIButton *copyButton = [UIButton addToView:oldUIDView];
    [copyButton addTarget:self action:@selector(didClickCopyButton) forControlEvents:UIControlEventTouchUpInside];
    [copyButton setImage:[UIImage imageNamed:@"mine_copy_icon"] forState:UIControlStateNormal];
    [copyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(15);
        make.centerY.offset(0);
        make.width.height.offset(16);
    }];
    
    UILabel *oldUIDValueLabel = [UILabel lableWithSuperView:oldUIDView font:UIFontMake(14) color:UIColor.tj_333333Color title:_userModel.uid textAlignment:NSTextAlignmentLeft];
    [oldUIDValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(copyButton.mas_left).inset(5);
        make.centerY.offset(0);
    }];
    
    UIView *lastView = nil;
    
    if (_userModel.isCanModify) {
        
        UILabel *UIDLabel = [UILabel lableWithSuperView:contentView font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:@"New UID" textAlignment:NSTextAlignmentLeft];
        [UIDLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(leftRightMargin);
            make.top.equalTo(oldUIDView.mas_bottom).offset(20);
        }];
        
        UIView *UIDView = [UIView addToView:contentView];
        UIDView.addCornerRadius(10);
        UIDView.backgroundColor = UIColor.tj_F6F6F6Color;
        [UIDView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(leftRightMargin);
            make.top.equalTo(UIDLabel.mas_bottom).offset(20);
            make.height.offset(50);
        }];
     
        QMUITextField *textField = [QMUITextField addToView:UIDView];
        if (_userModel.isCanModify) {
            textField.placeholder = @"Letter and number";
        } else {
            textField.placeholder = [NSString stringWithFormat:@"Will be modified at %@ time", _userModel.modifyDate];
            textField.userInteractionEnabled = NO;
        }
        textField.font = UIFontMake(14);
        textField.maximumTextLength = 12;
        textField.delegate = self;
        textField.keyboardType = UIKeyboardTypeASCIICapable;
        textField.returnKeyType = UIReturnKeyDone;
        [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.offset(10);
            make.right.inset(15);
            make.height.offset(40);
        }];
        
        HJUIDTipView *tipView = [[HJUIDTipView alloc] init];
        tipView.isError = YES;
        [tipView.closeButton addTarget:self action:@selector(didClickCloseButton) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:tipView];
        [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(UIDView);
            make.height.offset(0);
            make.top.equalTo(UIDView.mas_bottom).offset(10);
        }];
        
        lastView = UIDView;
        _textField = textField;
        _tipView = tipView;
        _UIDView = UIDView;
    } else {
        
        UIView *unableModifiedView = [self unableModifiedView];
        [contentView addSubview:unableModifiedView];
        [unableModifiedView addTapGesturesWithTarget:self action:@selector(tapUnableModifiedView)];
        [unableModifiedView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(oldUIDView);
            make.height.offset(40);
            make.top.equalTo(oldUIDView.mas_bottom).offset(10);
        }];
        lastView = unableModifiedView;
    }

    UIView *ruleView = [self addRuleView];
    [contentView addSubview:ruleView];
    [ruleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.equalTo(lastView.mas_bottom).offset(30);
        make.bottom.equalTo(ruleView.subviews.lastObject.mas_bottom).offset(20);
    }];
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    contentSize = CGSizeMake(self.mainView.bounds.size.width, contentView.subviews.lastObject.tj_MaxY + 10);
    self.mainView.contentSize = contentSize;
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(contentSize.height);
    }];
    
    _doneButton = doneButton;
    _oldUIDValueLabel = oldUIDValueLabel;

}

- (UIView *)addRuleView {
    
    UIView *ruleView = [[UIView alloc] init];
    ruleView.layer.borderColor = UIColor.tj_separatorColor.CGColor;
    ruleView.layer.cornerRadius = 10;
    ruleView.layer.masksToBounds = YES;
    ruleView.layer.borderWidth = 0.7;
 
    UILabel *ruleLabel = [UILabel lableWithSuperView:ruleView font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:@"Tips:" textAlignment:NSTextAlignmentLeft];
    [ruleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.left.offset(15);
    }];
 
    UILabel *ruleContentLabel = [UILabel lableWithSuperView:ruleView font:UIFontMake(12) color:UIColor.tj_868391Color title:@"• The UlD can consist of any combination of 6 to 12characters from \"0-9\",\"a-z\", and \"A-Z\"\n• It's forbidden to use names of other people. trademarks, or names of registered companies for UlD\n• UlD must not be employed for impersonating others\n• Avoid using identifable information of others or misleading content in UID" textAlignment:NSTextAlignmentLeft];
    ruleContentLabel.numberOfLines = 0;
    ruleContentLabel.attributedText = [self attributedString:ruleContentLabel.text color:UIColor.tj_868391Color rangeString:@"• The UlD can consist of any combination of 6 to 12characters from \"0-9\",\"a-z\", and \"A-Z\"" rangeColor:UIColor.tj_333333Color];
    [ruleContentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ruleLabel.mas_bottom).offset(13);
        make.left.right.inset(15);
        make.bottom.inset(20);
    }];
    
    _ruleView = ruleView;
    return ruleView;
}

- (UIView *)unableModifiedView {
    UIView *view = [[UIView alloc] init];
    
    view.backgroundColor = UIColor.tj_FFF8F1Color;
    view.addCornerRadius(10);
    [view clipsToBounds];
    
    UIImageView *iconImageView = [UIImageView addToView:view];
    iconImageView.image = [UIImage imageNamed:@"warn_icon"];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.centerY.offset(0);
        make.width.height.offset(20);
    }];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:view font:UIFontMediumMake(12) color:UIColor.tj_FF5100Color title:[NSString stringWithFormat:@"New UID: Will be modifed at %@", _userModel.modifyDate] textAlignment:NSTextAlignmentLeft];
    titleLabel.numberOfLines = 0;
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.inset(10);
        make.left.equalTo(iconImageView.mas_right).offset(10);
    }];
    
    UIImageView *infoImageView = [UIImageView addToView:view];
    infoImageView.image = [UIImage imageNamed:@"red_info-circle"];
    [infoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(5);
        make.centerY.offset(0);
    }];
    
    return view;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    if (textField.text.length >= 6) {
        _doneButton.enabled = YES;
        if (self.showTip) {
            self.tipView.isError = NO;
        } else {
            self.showTip = YES;
        }
    } else {
        _doneButton.enabled = NO;
        self.showTip = YES;
        self.tipView.isError = YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *allowedCharacters = [NSCharacterSet alphanumericCharacterSet];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:string];
    return [allowedCharacters isSupersetOfSet:characterSet];
}

- (NSAttributedString *)attributedString:(NSString *)string  color:(UIColor *)color rangeString:(NSString *)rangeString rangeColor:(UIColor *)rangeColor {
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 3;
    paragraphStyle.paragraphSpacing = 8;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSDictionary *attributeDict = @{
        NSFontAttributeName: UIFontMake(12),
        NSForegroundColorAttributeName:color,
        NSParagraphStyleAttributeName:paragraphStyle
    };
    
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:attributeDict];
    [attributeStr addAttributes:@{
        NSForegroundColorAttributeName: rangeColor,
    } range:[string rangeOfString:rangeString]];
    return attributeStr;
}

- (void)tapUnableModifiedView {
    [HJAlertController alertInController:self title:@"Change Notice" message:@"UID is the unique proof of your account, and can only be changed once a year" left:nil right:^(HJAlertAction * _Nonnull action) {
        action.title = @"OK";
        action.titleColor = UIColor.tj_mainColor;
    }];
}

- (void)didClickDoneButton {
    
    [HJAlertController alertInController:self title:@"Confirm Change" message:@"UlD is the unique proof of your account, and can only be changed once a year. Do you confirm the change?" left:^(HJAlertAction * _Nonnull action) {
        action.title = @"Cancel";
        action.titleColor = UIColor.tj_868391Color;
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"OK";
        action.titleColor = UIColor.tj_mainColor;
        [action setHandler:^{
            [self.view endEditing:YES];
            [HJHUD showLoadingInView:self.view];

            NSString *UID = self.textField.text;
            [HJMinePresent modifyUID:UID complete:^(NSError * _Nullable error) {
                if (error) {
                    [HJHUD showErrorMessage:error.localizedFailureReason];
                    return;
                }
                
                if (self.complete) {
                    self.complete(UID);
                }
        
                
                [HJHUD showSucceedMessage:@"Successful operation"];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }];
    }];
}

- (void)didClickCloseButton {
    self.showTip = NO;
}

- (void)setShowTip:(BOOL)showTip {
    if (showTip == _showTip) return;
    
    _showTip = showTip;
    
    [UIView animateWithDuration:0.25 animations:^{
        if (showTip) {
            [self.tipView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(self.tipViewH);
            }];
            [self.ruleView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.inset(leftRightMargin);
                make.top.equalTo(self.tipView.mas_bottom).offset(30);
                make.bottom.equalTo(self.ruleView.subviews.lastObject.mas_bottom).offset(20);
            }];
        } else {
            [self.tipView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(0);
            }];
            [self.ruleView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.inset(leftRightMargin);
                make.top.equalTo(self.UIDView.mas_bottom).offset(30);
                make.bottom.equalTo(self.ruleView.subviews.lastObject.mas_bottom).offset(20);
            }];
        }
        
        [self.ruleView.superview setNeedsLayout];
        [self.ruleView.superview layoutIfNeeded];
    }];
}
 
- (void)didClickCopyButton {
    [HJTools copyStringToPasteboard:HJUserInfo.no];
    [HJHUD showSucceedMessage:@"Copied successfully"];
}
 
- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
